package com.destroyer.system.wechat.config;

import com.destroyer.common.util.PathUtil;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.util.IOUtil;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;

/**
 * 标题：WechatPaymentsConfig
 * 说明：微信支付配置
 * 时间：2024/3/12
 * 作者：admin
 */
@Configuration
public class WechatPaymentsConfig implements Serializable {
    private static final long serialVersionUID = -1;

    @Autowired
    private WechatConfig weChatConfig;


    /**
     * 获取平台证书的RSA配置（自动更新平台证书）
     * @return
     */
    @Bean
    @Lazy(false) // 默认情况下，Spring Boot 2.4+ 需要加上此注解确保在启动时初始化
    public Config getWechatRsaAutoCertificateConfig() {
        // 一个商户号只能初始化一个配置，否则会因为重复的下载任务报错
        // 获取当前类的类加载器
        ClassLoader classLoader = getClass().getClassLoader();
        // 打开资源文件作为输入流
        InputStream inputStream = classLoader.getResourceAsStream(PathUtil.getResourcesPathFromClassPath(weChatConfig.getPrivateKeyPath()));
        String privateKey = "";
        try {
            privateKey = IOUtil.toString(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Config rsp =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(weChatConfig.getMchid())
                        .privateKey(privateKey)
                        .merchantSerialNumber(weChatConfig.getMerchantSerialNumber())
                        .apiV3Key(weChatConfig.getApiV3Key())
                        .build();
        return rsp;
    }



    /**
     * 获取Jsapi服务
     * @return
     */
    @Bean
    @Lazy(false)
    public JsapiService getWechatJsapiService(){
        JsapiService rsp = new JsapiService.Builder().config(this.getWechatRsaAutoCertificateConfig()).build();
        return rsp;
    }


    /**
     * 获取Jsapi扩展服务
     * @return
     */
    @Bean
    @Lazy(false)
    public JsapiServiceExtension getWechatJsapiServiceExtension(){
        JsapiServiceExtension rsp = new JsapiServiceExtension.Builder().config(this.getWechatRsaAutoCertificateConfig()).build();
        return rsp;
    }




}
